package com.epin.business.commons.service.impl;


import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.epin.base.enums.commons.StatusEnum;
import com.epin.base.exception.check.RecordQuoteException;
import com.epin.business.commons.dao.UploadFileMapper;
import com.epin.business.commons.entity.UploadFile;
import com.epin.business.commons.service.UploadFileService;
import com.feilong.core.Validator;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 附件上传表 服务实现类
 * </p>
 *
 * @author fujiajun
 * @since 2017-10-10
 */
@Service
public class UploadFileServiceImpl extends ServiceImpl<UploadFileMapper, UploadFile> implements UploadFileService {
	
	
	private static final String FILE_NAME = "附件";
	
	
	/**
	 * <p>通过逻辑地址获取文件名</p>
	 */
	@Override
	public String selectFileNameByLogicPath(String logicPath) {
		
		if (Validator.isNullOrEmpty(logicPath)) {
			return FILE_NAME;
		}
		
		Map<String, Object> params = new HashMap<>();
		params.put("logicPath", logicPath);
		
		String result = baseMapper.selectFileName(params);
		
		return Validator.isNotNullOrEmpty(result) ? result : FILE_NAME;
	}
	
	
	/**
	 * <p>根据ID删除文件</p>
	 */
	@Override
	@Transactional(rollbackForClassName = "Exception")
	public boolean deleteFilesByIds(List<Integer> ids) throws RecordQuoteException {
		
		// 若文件不是都处于过期状态，则不能删除（即存在引用）
		if (!this.checkFilesIsStatus(ids, StatusEnum.DISABLE)) {
			throw new RecordQuoteException("出现启用的文件，不能删除");
		}
		
		return this.deleteBatchIds(ids);
	}
	
	
	/**
	 * <p>根据ID检测文件是否都处于此状态</p>
	 * 
	 * @param ids 文件ID数组
	 * @param status 检测状态
	 * 
	 * @return boolean
	 * 
	 * @author fujiajun
	 * @since 2017-10-27
	 */
	private boolean checkFilesIsStatus(List<Integer> ids, StatusEnum status) {
		
		if (Validator.isNullOrEmpty(ids) || Validator.isNullOrEmpty(status)) {
			return false;
		}
		
		int count = baseMapper.countFilesStatusById(ids, status.val());
		
		return count == ids.size() ? true : false;
	}
}
